package com.blog.common.core.utils;

/**
 * TODO
 *
 * @author Valerie
 * @date 2023/2/19
 **/

import com.alibaba.fastjson2.JSONObject;
import com.blog.common.core.utils.ip.IpUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 获取地址类
 *
 * @author Vivian
 */
@Slf4j
public class AddressUtils {


    // IP地址查询
    private static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    /**  未知地址 */
    private static final String UNKNOWN = "XX XX";

    private static final RestTemplate REST_TEMPLATE = new RestTemplate();

    public static String getRealAddressByIp(String ip) {
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        //ture：获取ip地址开关
        try {
            Map<String, String> params = new HashMap<>(16);
            params.put("ip", ip);
            ResponseEntity<String> forEntity = REST_TEMPLATE.getForEntity(IP_URL + "?ip={ip}&json=true", String.class, params);
            String rspStr = forEntity.getBody();
            if (StringUtils.isEmpty(rspStr)) {
                log.error("获取地理 位置异常 {}", ip);
                return UNKNOWN;
            }
            IpEntity ipEntity = JSONObject.parseObject(rspStr, IpEntity.class);
            if (Objects.isNull(ipEntity)){
                log.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }
            String region = ipEntity.getPro();
            String city = ipEntity.getCity();
            return String.format("%s %s", region, city);
        } catch (Exception e) {
            log.error("获取地理位置异常 {}", ip);
        }
        return UNKNOWN;
    }

    @Data
    public static class IpEntity {
        private String ip;//IP地址
        private String pro;//省
        private String proCode;//省编码
        private String city;//城市
        private String cityCode;//城市编码
        private String region;//区
        private String regionCode;//区编码
        private String addr;//详细地址 + 运营商
        //主要用于接参，无实际意义
        private String regionNames;
        private String err;
    }
}
